package com.tianquan.client;


import com.tianquan.client.handler.ClientChannelInboundHandlerAdapterHandler;
import com.tianquan.client.handler.PullServiceResponseMessageHandler;
import com.tianquan.client.handler.ServiceUpdateMessageHandler;
import com.tianquan.common.instance.ServiceInstance;
import com.tianquan.common.protocol.MessageCodecSharable;
import com.tianquan.common.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * @Author: tianquan
 * @date: 2024-11-03  09:01
 * @Description: 客户端
 */
@Slf4j
public class PBankClient {
    // 服务端地址
    private final String address;
    // 服务端端口
    private final int port;
    // 当前客户端实例
    private ServiceInstance serviceInstance;
    // 事件处理组
    private final NioEventLoopGroup group;
    // 日志处理器
    private LoggingHandler LOGGING_HANDLER;
    // 消息编解码器
    private MessageCodecSharable MESSAGE_CODEC;
    // 客户端处理器
    private ClientChannelInboundHandlerAdapterHandler CLIENT_INBOUND_HANDLER;
    // 获取服务响应处理器
    private PullServiceResponseMessageHandler PULL_RESPONSE_HANDLER;
    // 服务变更处理器
    private ServiceUpdateMessageHandler SERVICE_UPDATE_HANDLER;
    // 是否已启动
    private final boolean started = false;

    private PBankClient(String user, String password, String address, int port, String serverName,int weight) {
        this.address = address;
        this.port = port;
        // 设置服务名名称
        serviceInstance = new ServiceInstance(serverName, UUID.randomUUID().toString(),weight);
        group = new NioEventLoopGroup();
        LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MESSAGE_CODEC = new MessageCodecSharable();
        // 客户端处理器 设置登录名和密码以及服务实例
        CLIENT_INBOUND_HANDLER =
                new ClientChannelInboundHandlerAdapterHandler(user, password, serviceInstance);
        PULL_RESPONSE_HANDLER = new PullServiceResponseMessageHandler();
        SERVICE_UPDATE_HANDLER = new ServiceUpdateMessageHandler();
    }

    public static class PBankClientBuilder {
        private String user;
        private String password;
        private String address;
        private int port;
        private String serverName;
        // 权重默认1
        private int weight = 1;

        public static PBankClientBuilder builder() {
            return new PBankClientBuilder();
        }

        public PBankClientBuilder user(String user) {
            this.user = user;
            return this;
        }

        public PBankClientBuilder password(String password) {
            this.password = password;
            return this;
        }

        public PBankClientBuilder address(String address) {
            this.address = address;
            return this;
        }

        public PBankClientBuilder port(int port) {
            this.port = port;
            return this;
        }

        public PBankClientBuilder serverName(String serverName) {
            this.serverName = serverName;
            return this;
        }

        public PBankClientBuilder weight(int weight) {
            this.weight = weight;
            return this;
        }

        public PBankClient build() {
            if (user == null || password == null || address == null || port == 0 || serverName == null) {
                throw new IllegalArgumentException("参数不能为空");
            }
            return new PBankClient(user, password, address, port, serverName,weight);
        }
    }

    // 建立连接
    public void startClient() {
        // 一个客户端只能启动一次
        if (started) {
            throw new IllegalStateException("client already started");
        }
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    // ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(PULL_RESPONSE_HANDLER);
                    ch.pipeline().addLast(SERVICE_UPDATE_HANDLER);
                    ch.pipeline().addLast(CLIENT_INBOUND_HANDLER);
                }
            });
            Channel channel = bootstrap.connect(address, port).channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
